# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(plyr)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(tidyverse)
library(magrittr)
library(extrafont)

numDeal <- function(x) {
  # if (x > 2) {
  #     2
  # } else if (x < (- 2)) {
  #     - 2
  # } else x
  x
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "Class_Color.txt", type = "character", help = "sample color file"),
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--pc", default = "", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))
source(str_c(scriptPath, "/parse_config_json.R"))
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote)) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

sampleIds <- sampleInfo %>%
  arrange(ClassNote) %>%
  .$SampleID

sampleColDf <- tibble(ClassNote = plotConfigJson$color$groups, col = plotConfigJson$color$colors)
sampleColDf
sampleCols <- sampleColDf %>%
  deframe()

configJson <- fromJSON(opt$cc)

pValue <- configJson$pValue %>%
  as.numeric()
useFdr <- configJson$useFdr %>%
  as.logical()
tmpFdr <- configJson$fdr %>%
  as.numeric()
fdr <- if (useFdr) {
  tmpFdr
}else 1
log2FC <- configJson$log2FC

baseFamily <- fontFamily

diffName <- read_csv("Diff_Met_Test.csv") %>%
  .$Metabolite

parent <- "./"
pdfFileName <- paste0(parent, "/Z_Score_Plot.pdf")
fileName <- paste0(parent, "/AllMet_Z_Score.csv")

if (length(diffName) == 0) {
  quit(status = 0)
}

orignalData <- read_tsv(opt$i) %>%
  rename(Metabolite = 1) %>%
  select(c("Metabolite", sampleIds)) %>%
  filter(Metabolite %in% diffName)

orignalData

data <- orignalData %>%
  gather("SampleID", "Value", -Metabolite, factor_key = T) %>%
  spread(Metabolite, "Value") %>%
  mutate_at(vars(-"SampleID"), scale) %>%
  mutate_at(vars(-"SampleID"), function(x) {
    x1 <- x %>%
      unlist() %>%
      map_dbl(numDeal)
    return(x1)
  }) %>%
  as.data.frame() %>%
  arrange(factor(SampleID, levels = sampleIds)) %>%
  column_to_rownames("SampleID")

write.csv(data, fileName)

groups <- unique(sampleInfo$ClassNote)

group1Name <- groups[1]
group2Name <- groups[2]

sortData <- orignalData %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    group1Sample <- sampleInfo %>%
      filter(ClassNote == groups[1]) %>%
      .$SampleID
    group2Sample <- sampleInfo %>%
      filter(ClassNote == groups[2]) %>%
      .$SampleID
    group1Data <- result[group1Sample] %>% unlist
    group2Data <- result[group2Sample] %>% unlist
    mean1Name <- paste0(group1Name, ".Mean")
    result[, mean1Name] <- mean(group1Data)
    mean2Name <- paste0(group2Name, ".Mean")
    result[, mean2Name] = mean(group2Data)
    result$FC <- result[, mean2Name] / result[, mean1Name]
    result[, "min1"] <- min(group1Data)
    result[, "min2"] <- min(group2Data)
    result[, "logFC"] <- log(result[, "FC"])
    result
  }) %>%
  select(-sampleIds) %>%
  arrange(desc(logFC))

options(tibble.print_max = 20)

plotData <- data %>%
  rownames_to_column("SampleID") %>%
  gather("Metabolite", "Value", -SampleID) %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  mutate(Metabolite = factor(Metabolite, levels = sortData$Metabolite))

p <- ggplot(plotData, mapping = aes(x = Value, y = Metabolite, fill = ClassNote)) +
  ylab("") +
  xlab("Z Score") +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = xFont, hjust = 1, vjust = 1), legend.position = 'right',
        legend.text = element_text(size = legendFont), legend.title = element_text(size = legendTitleFont), axis.text.y = element_text(size = yFont),
        axis.title.y = element_text(size = 11), axis.title.x = element_text(size = xTitleFont), panel.grid.major.x = element_blank(),
        panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(),
        panel.grid.major.y = element_line(linetype = 2, color = "#BEBEBE"),
        plot.title = element_text(hjust = 0.5, size = mainTitleFont)
  ) +
  geom_point(shape = 21, color = "black", size = 2, alpha = 0.75, stroke = 0.2)

if (!is.na(mainTitle)) {
  p <- p + ggtitle(mainTitle)
}

if (!is.na(legendTitle)) {
  p <- p +
    scale_fill_manual(legendTitle, values = sampleCols)
}else {
  p <- p +
    scale_fill_manual("", values = sampleCols)
}

pdfFileName <- paste0(parent, "/Z_Score_Plot.pdf")
ggsave(limitsize = FALSE, pdfFileName, p, width = width, height = height)





